#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @author: zzll0909
# @file: 2.py
# @time: 2024/06/14
# @software: VS Code
from typing import Optional


class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        # 最终结果
        result = None
        # 当前操作节点
        node = None
        plus = 0
        while l1 or l2:
            v1 = l1.val if l1 else 0
            v2 = l2.val if l2 else 0
            value = v1 + v2 + plus
            if value >= 10:
                value %= 10
                plus = 1
            else:
                plus = 0
            # 添加个位值
            if not result:
                result = ListNode(value)
                node = result
            # 添加高位值
            else:
                node.next = ListNode(value)
                node = node.next
            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None
        # 如果还有进位，补一个
        if plus == 1:
            node.next = ListNode(1)
        return result


if __name__ == "__main__":
    pass
